/**
 * jingoalNewTree 支持选择部门和职务
 * 
 * nodeType: 选择节点的类型
 *  	  0: 员工，1: 部门，2：职务 , 3:公司
 * 
 **/

function getTimedUrl(url){
	return url + (url.indexOf('?') > 0 ? '&' : '?') + 't=' + new Date().getTime();
}

//移除该树
function removeJingoalTreeFromWindow(suffix){
	$.fn.zTree.destroy('jingoalTree' + suffix);
	$("#jingoalTreeModal" + suffix).modal("hide").remove();
	$("#popup" + suffix).remove();
	window.dialogNewTree = null;
};

/**切换了列表类型或者是选项卡时清除搜索下拉 和 搜索框的值*/
function resetSearchFilter(suffix){
	$("#jingoalTreeSearchInput" + suffix).val("");
	$("#jingoalTreeSearchInput" + suffix).blur();
}

// 重设树的高度
function resizeJingoalTreeScrollPanel(treeId, opt, suffix) {
	var h = opt.height;
	var t = $("#" + treeId);
	/*if ($.browser.ie7) {
		var aw = t.data("oldWidth");
		if (!aw) {
			t.data("oldWidth", true)
			t.width(t.width() - 2);
		}
	}*/
	t.height(h);
};

var newtree_lang = {
	dept : "部门",
	duty : "职务",
	employee : "人员",
	empty_result : "没有找到匹配结果",
	placeholder : "输入员工、部门或职务名称",
	find : "找到",
	has_selected : "已选",
	add : "添加",
	maxSelectTip0 : "至多可选",
	maxSelectTip1 : "条结果" ,
	frEnterprise : "友好企业",
	noPosition: "未分配职务",
	defineGroup :"自定义组",
	allEmpText : "全体员工"
};

window.JingoalTree || (window.JingoalTree = (function(){

	var globalSuffix = 0,
		_nodes = {}, // 人员集合
		NODE_TYPE_EMPLOYEE = 0, NODE_TYPE_DEPT = 1, NODE_TYPE_DUTY = 2, NODE_TYPE_COMPANY = 3;  // 树节点类型， 0: 员工， 1：部门，2：职务  3:公司

	function getNode(uid){
		if (_nodes[uid]) {
			return _nodes[uid];
		} else {
			return null;
		}
	}
	
	function Node(id, name, fromEnc, type){
		this.id = typeof(id) === 'undefined' ? 0 : id;
		this.name = typeof(name) === 'undefined' ? '' : name;
		this.fromEnc = typeof(fromEnc) === 'undefined' ? 0 : fromEnc;
		this.type = typeof(type) === 'undefined' ? 0 : type;
	}
	
	function createNode(id, name, fromEnc, type){
		var node = getNode(id);
		if (node == null) {
			type = getNodeType(type);
			node = _nodes[id] = new Node(id, name, fromEnc, type);
		}
		return node;
	}
	
	function getNodeType(type){
		switch (type) {
		case NODE_TYPE_DEPT:
			return 'dept';
			break;
		case NODE_TYPE_DUTY:
			return 'duty';
			break;
		case NODE_TYPE_COMPANY : 
			return "company" ;
		default:
			return 'employee';
			break;
		}
	}
	
	function getNodeName(type){
		switch (type) {
		case NODE_TYPE_DEPT:
			return newtree_lang.dept;
			break;
		case NODE_TYPE_DUTY:
			return newtree_lang.duty;
			break;
		default:
			return newtree_lang.employee;
			break;
		}
	}
	
	/**
	 * 过滤节点，如果节点下没有子元素，则设置该节点的isparent为false，并修改节点图片为iconSkin
	 * @param node
	 * @param iconSkin
	 * @param treeType
	 */
	function _filterNode(node, iconSkin, treeType){
		node.iconSkin = iconSkin;
		
		if (treeType == "byEmployee" && (node.isParent && node.children.length == 0)) {
			node.nocheck = true;
		} else if (!node.children || node.children == null || node.children.length == 0) {
			node.nocheck = false;
			return ;
		}
		for( var i = 0 ; i < node.children.length;i++){
			_filterNode(node.children[i],iconSkin, treeType);
		}
	}
	
	return function(opt) {
		// 默认设置
		var option = {
			selectedParentDept: false,   //选部门  右边table 是否选中父节点 --
			selectedOnlyOne   : false,   //选部门  右边table 是否只能选中勾选的节点，--
			clearCompanyAll   : true,    //当点击全体员工时，取消一个人员或部门，其他人员或部门全部选中
			treeTitle: '', // 弹出树标题
			showSend : false, // 是否显示消息设置
			treeType : '',
			isDialog : true, 
			permId : '',     // 权限
			checkedNodes : '',  //json字符串
			height : 209,     // 高度
			itemUrl : '',
			placeholder : newtree_lang.placeholder, //msg: '输入员工、部门或职务名称',
			treeFilterType: '0,1,2', //0： 人员， 1：部门， 2：职务
			showEnc: false, //是否支持选择 '友好企业', 如果不支持选择人员，该属性无效[默认不支持]
			allDept: false, // 是否获取所有的部门, 如果不支持部门选择，该属性无效
			maxSelect: 200,   // 可以选择最大的节点数
			maxSelectTip: 190 , // 提示时选择的最大节点数
			isAll : false // 勾选公司   true: 全部员工  false: 显示所有员工
		};
		$.extend(option, opt);
		// 初始化树 配置
		var setting = {
			check: {
				enable: option.hasCheckBox,
				nocheckInherit: false
			},
			data: {
				simpleData: {
					enable: false
				}
			},
			callback: {
				onCheck: function(event, treeId, treeNode) {
					// 处理树节点选中
					function handleNode(node){
						if(node.isParent){
							if(option.isAll && node.type == NODE_TYPE_COMPANY && node.level == 0){
								if(node.checked ){
									clearAll();
									addNode(createNode(node.id, newtree_lang.allEmpText, node.nec, node.type));
									JingoalTree.companyId = node.id ; 
									//如果选择部门，并且只能单选部门，当点击公司时，取消其他的勾选状态，留下公司的勾
									if(option.treeType == "byDept" && option.selectedOnlyOne){
										clearSelect();
									}
									
								} else {
									clearAll();
									delete JingoalTree.companyId ;
								}
							}else{
								//选中父节点的记录 --
								if(option.selectedParentDept && option.treeType == "byDept") {
									selectedNode(node);
								}
								
								//只选中父节点的记录--
								if(option.treeType != "byDept" || !option.selectedOnlyOne){
									var childs = node.children ;
									for(var i = 0;i < childs.length;i++){
										handleNode(childs[i]);
									}
								}
							}
						} else {
							selectedNode(node);
						}
					}
					
					//添加或删除 节点 --
					function selectedNode(node) {
						if (node.checked) {
							var flag = false;
							//取消掉公司的勾选
							if(option.treeType == "byDept" && option.selectedOnlyOne){
								flag = true;
							}
							removeNode(JingoalTree.companyId+"-"+getNodeType(NODE_TYPE_COMPANY) ,flag); 
							delete JingoalTree.companyId ;
							if(option.treeType == "byEmployee" && (node.type ==  NODE_TYPE_DEPT || node.type == NODE_TYPE_DUTY )){
								return ;
							}
						    addNode(createNode(node.id, node.name, node.nec, node.type));
						} else {
							var nodeType = getNodeType(node.type);
							removeNode(node.id+"-"+nodeType,false);
							if(!option.clearCompanyAll && !!JingoalTree.companyId){
								clearAll()
								selectPartCompany();
							}else{
								removeNode(JingoalTree.companyId+"-"+getNodeType(NODE_TYPE_COMPANY) ,true);
							}
							delete JingoalTree.companyId ;
						}
					}
					//先选择全体员工   后取消一个人，或一个部门，选中其他的所有人--
					function selectPartCompany(){
						var tree = $.fn.zTree.getZTreeObj(treeId);
						var checkedNodes = tree.getCheckedNodes(true);
						for(var j = 0,len = checkedNodes.length; j < len; j++){
							var node = checkedNodes[j];
							if(!node.getCheckStatus().half){
								handleNode(node);
							}
						}
					}
					
					//部门且可单选部门时，选择公司去掉 其他部门的勾
					function clearSelect(){
						var tree = $.fn.zTree.getZTreeObj(treeId);
						var checkedNodes = tree.getCheckedNodes(true);
						for(var j = 0,len = checkedNodes.length; j < len; j++){
							var node = checkedNodes[j];
							if(node.id != JingoalTree.companyId){
								node.checked = false;
								tree.updateNode(node);
							}
						}
					}
					
					handleNode(treeNode);
				},
				onClick: function(event, treeId, treeNode) {
					/*if(type == 'byDept'){
						$("#singleSelectName" + suffix).val(treeNode.name);
						$("#singleSelectId" + suffix).val(treeNode.id);
					} else if (treeNode != null && !treeNode.isParent ) {
						if($.type(option.onUserClick) === 'function'){
							option.onUserClick(treeNode);
						}
					}*/
				},
				onDblClick: function(event, treeId, treeNode) {
					if (treeNode != null && $.type(option.onUserDblClick) === 'function'){
						option.onUserDblClick(treeNode);
					}
				}
			},
			view: {
				selectedMulti : false
			}
		};
		
		var appBase = 'globalCp',
			suffix = globalSuffix++,
			treeId = "jingoalTree" + suffix,
			nodes = new Array(),
			type = option.treeType != '' ? option.treeType : "byEmployee", //默认根据部门获取所有的员工
			treeData = null;
	
		var parentLevel = 0,
			parentId = 0;
			
		if (option.isDialog) {
			/*if(!JingoalTree.template){
				$.post(appBase + '/public/v1/common/tree/dialogJingoalTree.jsp?v=1' ,function(html){
						JingoalTree.template = html;
					}).done(function(){
						//启用莲花圈
						setTimeout(function(){
							initTree();
						},10);
				});
			} else {
				initTree();
			}*/
			initTree();
			window.dialogNewTree = this;
		};
		
		
		/**
		 * 一个页面中可以能有多个tree，为了相互不影响，需要修改某些需要操作的dom元素id
		 */
		function initDom() {
			$('.replaceid').each(function(index, item){
				item.id = item.id + suffix;
			});
			$('.replacename').each(function(index, item){
				item.name = item.name + suffix;
			});
			
			$("#treeTitle" + suffix).text(option.treeTitle);
			
			if (option.showSend) {
				$("#chooseSend" + suffix).css("display", "block");
			} else {
				$("#chooseSend" + suffix).css("display", "none");
			}
			if(!option.showEnc){
				$("#encCompany" + suffix).css("display", "none");
			}
			// 选择树的类型
			if (option.treeFilterType) {
				if (option.treeFilterType.indexOf('0') == -1) {
					$("#orgEmp"+suffix).addClass('hide');
					$("#jingoalTreeSubtab"+suffix).addClass('hide');
				}
				if (option.treeFilterType.indexOf('1') == -1) {
					$("#orgDept"+suffix).addClass('hide');
				}
				if (option.treeFilterType.indexOf('2') == -1) {
					$("#orgDuty"+suffix).addClass('hide');
				};
			};
			
			selectPanel(type);
		}
		
		/**
		 * 初始化树
		 */
		function initTree(){
			var d = {
					treeType : type ,
					isAllDept : option.allDept ,
					permId : option.permId ,
					treeFilter : option.treeFilter === 'string' ? option.treeFilter : "ownCompany",
					version: type == "byDept" ? (JingoalTree.deptVersion ? JingoalTree.deptVersion : "0") : (JingoalTree.employeeVersion ? JingoalTree.employeeVersion : "0")
						
				};
			//根据版本号判断 组织结构是否更新
			//$.post(appBase + '/common/tree/getDialogtree.do' , d , function(data){

				var data = option.globaldata;


				// 初始化页面元素
				initDom();
				// 预选人员
			    reverseSelect(treeId, option.checkedNodes);
			    if (option.itemUrl != '') {
			    	$("#defaultUserNamesData").remove();
					$("#defaultUserIdsData").remove();
			    }
				// 调整尺寸 考勤版本把它注释掉，不知道为什么要加它
				//setTimeout(function(){resizeJingoalTreeScrollPanel(treeId, option, suffix);}, 0);
				bindEvent();
				bindEventToTab();
				
				bindEventsToSearch();
					
				if (option.hasRightPanel) {
					bindEventToRight();
				}
				if (option.showSend) {
					bindSendClick();
				}
				setData(data , type);
			//});
		}
		
		/**
		 * 填充树
		 * @param data
		 * @param ids
		 * @param showFilter
		 * @param names
		 */
		function setData(data, treeType, showFilter) {
		    //还原勾选效果 在选择部门的时候可能修改了该值--
			setting.check.chkboxType = undefined;
			//判断请求是否返回数据,来更新缓存(包含三个缓存 员工,部门,职务)
			if(data.data && treeType == 'byEmployee' ){
				//选择员工按本企业做缓存
				(!showFilter || showFilter == "ownCompany") && (JingoalTree.employeeData = data.data);
			} else if(data.data && treeType == 'byDept'){
				JingoalTree.deptData = data.data;
			} else if(data.data && treeType == 'byDuty'){
				JingoalTree.dutyData = data.data;
			}
			treeData = treeType == 'byEmployee' && JingoalTree.employeeData 
						|| treeType == 'byDept' && JingoalTree.deptData
						|| treeType == 'byDuty' && JingoalTree.dutyData;
			resetSearchFilter(suffix);
			
			//选择员工不是按本企业获取获取获取数据
			if( treeType == 'byEmployee' && showFilter && showFilter != "ownCompany") treeData = data.data;
			
			if (treeType == 'byEmployee') {
				//选择人员记录版本号,用做请求人员是否返回数据判断
				(!showFilter || showFilter == "ownCompany") && (JingoalTree.employeeVersion = data.version) ;
				
				if(treeData[0].name === "common.tree.frEnterprise")  treeData[0].name = newtree_lang.frEnterprise;
				if(treeData[0].name === "common.tree.defineGroup")  treeData[0].name = newtree_lang.defineGroup;
				_filterNode(treeData[0], '', treeType);
				
				//按员工选择并且可以选择全体员工 设置root节点类型为 3 
				if(option.isAll && (!showFilter || showFilter == "ownCompany")){
					treeData[0].type = NODE_TYPE_COMPANY ;
				}
			} else if(treeType == 'byDept') {
				//选择部门记录版本号,用做请求部门是否返回数据判断
				JingoalTree.deptVersion = data.version ;
				_filterNode(treeData[0], 'dept', treeType);
				
				//按部门选择并且可以选择全体员工 设置root节点类型为 3 --
				if(option.selectedParentDept){
					if(option.isAll && (!showFilter || showFilter == "ownCompany")){
						treeData[0].type = NODE_TYPE_COMPANY ;
					}
				}
				//部门可以选择父部门时，勾选子部门不会连接取消父部门
				if(option.selectedParentDept) {
					setting.check.chkboxType = { "Y" : "s", "N" : "s" };;
				}
				
				//如果选择部门只能选中一个--
				if(option.selectedOnlyOne === true){
					setting.check.chkboxType = { 'Y' : '', 'N' : '' };
				}
			} else {
				//选择职务记录版本号,用做请求职务是否返回数据判断
				JingoalTree.dutyVersion = data.version ;
				for(var i = 0 ; i < treeData[0].children.length ; i++){
					if(treeData[0].children[i].name === 'undefined'){
						treeData[0].children[i].name = newtree_lang.noPosition ;
					}
				}
			}
			treeData[0].iconSkin = "root";
			treeData[0].open = true;
			
			$.fn.zTree.init($("#" + treeId), setting, treeData);
		}
		
		/**
		 * 树初始化完成时预选择人员
		 * @param treeId
		 * @param checkedNodeStr
		 */
		function reverseSelect(treeId, checkedNodeStr) {
			if (checkedNodeStr !== '' && checkedNodeStr.length > 0) {
				
				var checkedNodes = $.parseJSON(JSON.stringify(checkedNodeStr));
				
				if(checkedNodes.length == 1 && checkedNodes[0].type == NODE_TYPE_COMPANY){
					addNode(createNode(checkedNodes[0].id, newtree_lang.allEmpText, checkedNodes[0].nec, checkedNodes[0].type));
					JingoalTree.companyId = checkedNodes[0].id;
				} else if(checkedNodes.length > 0){
					$.each(checkedNodes, function(i,item){
						addNode(createNode(item.id, item.name, item.nec, item.type));
					});
				}
			}
		}
		
		/**
		 * 绑定确定/取消 按钮事件
		 */
		function bindEvent(){
			$("#jingoalTreeCancel" + suffix).click(function() {
				removeJingoalTreeFromWindow(suffix);
				if(option.callCancelback){
					option.callCancelback();
				}
			});
			
			$("#jingoalTreeOk" + suffix).click(function() {
				if (nodes.length > option.maxSelect) {
					$('.notifications').remove();
					lab_mgtNotification({
						message:"<i class='commpic-warn'></i>" + newtree_lang.maxSelectTip0 + option.maxSelect + newtree_lang.maxSelectTip1, 
						type: 'error',
						position:"top-center",
						closable:false
					});
					return;
				}
				option.callback(window.dialogNewTree);
			});
		}
		
		/**
		 * 选项卡绑定事件
		 * @returns
		 */
		function bindEventToTab(){
			var treeArg = {
				treeType: 'byEmployee',
				treeFilter: 'ownCompany',
				permId: option.permId,
				isAllDept : option.allDept
			};
			
			// 人员筛选 过滤
			$("#jingoalTreeSubtab" + suffix + " > label").click(function(event){
				var filterType = $(event.target).data('type');
				switch (filterType) {
				case 'ownCompany':
					$("#ownCompany" + suffix + " > span:eq(0)").addClass("dialogtree-radioed");
					$("#encCompany" + suffix + " > span:eq(0)").removeClass("dialogtree-radioed");
					$("#customGroup" + suffix + " > span:eq(0)").removeClass("dialogtree-radioed");
					break;
				case 'encCompany':
					$("#encCompany" + suffix + " > span:eq(0)").addClass("dialogtree-radioed");
					$("#ownCompany" + suffix + " > span:eq(0)").removeClass("dialogtree-radioed");
					$("#customGroup" + suffix + " > span:eq(0)").removeClass("dialogtree-radioed");
					break;
				case 'customGroup':
					$("#customGroup" + suffix + " > span:eq(0)").addClass("dialogtree-radioed");
					$("#encCompany" + suffix + " > span:eq(0)").removeClass("dialogtree-radioed");
					$("#ownCompany" + suffix + " > span:eq(0)").removeClass("dialogtree-radioed");
					break;
				}
				
				treeArg.treeFilter = filterType;
				treeArg.version = filterType == "ownCompany" ? JingoalTree.employeeVersion : "4" ;
				treeFilter(treeArg);
			});
			
			// 选员工
			$("#orgEmp" + suffix).click(function() {
				//--
				option.treeType = treeArg.treeType = "byEmployee";
				//设置请求的版本号为 员工的版本号
				treeArg.version = treeArg.treeFilter == "ownCompany" ? JingoalTree.employeeVersion || "0" : "0" ;
				treeFilter(treeArg);
			});
			
			// 选部门
			$("#orgDept" + suffix).click(function() {
				//--
				option.treeType = treeArg.treeType = "byDept";
				//设置请求的版本号为 部门的版本号
				treeArg.version = JingoalTree.deptVersion || "1" ;
				treeFilter(treeArg);
			});
			
			//选职务
			$("#orgDuty" + suffix).click(function() {
				//--
				option.treeType = treeArg.treeType = "byDuty";
				//设置请求的版本号为 职位的版本号
				treeArg.version = JingoalTree.dutyVersion || "2" ;
				treeFilter(treeArg);
			});
		}
		
		/**
		 * 搜索的事件绑定
		 * @returns
		 */
		function bindEventsToSearch(){
			$("#jingoalTreeSearchInput" + suffix).keyup(function(event){
				var searchText = $.trim($(this).val());
				if (searchText == '' || searchText.length == 0) {
					$("#searchResult" + suffix).empty().hide();
					return;
				}
			});
			$("#jingoalTreeSearchInput" + suffix).keydown(function(event){
				// enter键搜索
				if (event.keyCode == 13) {
					event.preventDefault();
					search($.trim($(this).val()));
				}
			});
			
			$("#jingoalTreeSearchOk" + suffix).click(function() {
				search($("#jingoalTreeSearchInput" + suffix).val());
			});
			
			$("#jingoalTreeSearchInput" + suffix).attr('placeholder', option.placeholder);
		}
		
		function search(searchText){
			if (searchText == null || searchText.length == 0) {
				$("#searchResult" + suffix).empty().hide();
				return;
			} else {
				var searchResult = $("#searchResult" + suffix);
				if (searchResult.length == 0) {
					$(document.body).append("<div class='serch_panel replaceid hide' id='searchResult" + suffix + "'></div>");
				}
				$("#searchResult" + suffix).empty().hide();
				
				setTimeout(function(){
					$.ajax({
					  type: 'post',
		              url: appBase + '/common/tree/findTreeNodeByKey.do',
		              dataType: "json",
		              data: {key: searchText, permId: option.permId, type:option.treeFilterType},
		              success: function(data) {
		                	$(".searchList").empty();
		                	
		                	var employees = data.employee;
		                	var depts = data.dept;
		                	var duts = data.duty;
		                	
		                	if ((employees !== undefined && employees.length > 0) 
		                			|| (depts !== undefined && depts.length > 0) 
		                			|| (duts !== undefined && duts.length > 0)) {
								appendSearchResult(NODE_TYPE_EMPLOYEE, employees);
								appendSearchResult(NODE_TYPE_DEPT, depts);
								appendSearchResult(NODE_TYPE_DUTY, duts);
		                	} else {
		                		$("#searchResult" + suffix).empty();
		                		
		                		var $emptyResult = $("<div class='panel_Null'></div>")
		                			.append("<span class='panelSpan'>" + newtree_lang.empty_result + "</span>")
		                			.append("<span class='panel_line'></span>");
		                		$("#searchResult" + suffix).append($emptyResult); //msg: 没有找到匹配结果
		                	}
		                }
			        });
				}, 100);
				$("#searchResult" + suffix).show();
			}
		}
		
		// 拼装搜索结果
		function appendSearchResult(type, nodes){
			if (nodes == undefined) return;
			
			var $searchListDiv = $("#searchList" + type + suffix),
				$searchListHeader = $("#searchListHeader" + type + suffix), 
				$searchListUl = $("#searchListUl" + type + suffix);
			if ($searchListDiv.length == 0 && nodes.length > 0) {
				$searchListDiv = $("<div id='searchList" + type + suffix + "'></div>");
				$searchListHeader = $("<div id='searchListHeader" + type + suffix + "' class='panel_header'></div>"); 
				$searchListHeader.append("<span class='panelSpan'>" + newtree_lang.find + getNodeName(type) + nodes.length + "个</span>");
				$searchListHeader.append("<span class='panel_line'/>");
				
				$searchListUl = $("<ul class='searchList' id='searchListUl" + type + suffix + "'></ul>");
				
				$searchListDiv.append($searchListHeader);
				$searchListDiv.append($searchListUl);
				
				$("#searchResult" + suffix).append($searchListDiv);
			}
			
			$.each(nodes, function(i,item){
				// 添加搜索的结果
				var $searchLi = $("<li></li>")
					.append("<span style='*float:left;'>" + item.name + "</span>");
				
				if (isExistNode(item.id, type)){
					$searchLi.append("<span class='pull-right text' id='node_" + suffix + getNodeType(type) + item.id + "'>" + newtree_lang.has_selected + "</span>");
				} else {
					$searchLi.append("<span class='pull-right' id='node_" + suffix + getNodeType(type) + item.id + "'><button class='btn'>" + newtree_lang.add + "</button></span>");
				}
				$searchListUl.append($searchLi);
				
				$("#node_" + suffix + getNodeType(type) + item.id).click({node: item, type: type}, popUserClick);
			});
		}
		
		//搜索弹出框选择人员的事件
		function popUserClick(event) {
			var node = event.data.node;
			var type = event.data.type;
			removeNode(JingoalTree.companyId+"-"+getNodeType(NODE_TYPE_COMPANY) ,true); 
			addNode(createNode(node.id, node.name, node.nec, node.type));
			$("#node_" + suffix + getNodeType(type) + node.id).text(newtree_lang.has_selected).addClass("text");
		};
		
		function treeFilter(treeArg){
			$.post(getTimedUrl(appBase+"/common/tree/getDialogtree.do"), treeArg,
					function(data) {
						selectPanel(treeArg.treeType);
						setData(data, treeArg.treeType, treeArg.treeType == "byEmployee" ? treeArg.treeFilter : null);
				});
		}
		
		function selectPanel(treeType) {
			switch (treeType) {
			case 'byEmployee':
				resizeJingoalTreeScrollPanel(treeId, option, suffix);
				$("#jingoalTreeSubtab" + suffix).removeClass('hide');
				$("#orgEmp" + suffix).addClass("active");
				$("#orgDept" + suffix).removeClass("active");
				$("#orgDuty" + suffix).removeClass("active");
				break;
			case 'byDept':
				resizeJingoalTreeScrollPanel(treeId, {height: option.height + 30}, suffix);
				$("#jingoalTreeSubtab" + suffix).addClass('hide');
				$("#orgEmp" + suffix).removeClass("active");
				$("#orgDept" + suffix).addClass("active");
				$("#orgDuty" + suffix).removeClass("active");
				break;
			case 'byDuty':
				resizeJingoalTreeScrollPanel(treeId, {height: option.height + 30}, suffix);
				$("#jingoalTreeSubtab" + suffix).addClass('hide');
				$("#orgEmp" + suffix).removeClass("active");
				$("#orgDept" + suffix).removeClass("active");
				$("#orgDuty" + suffix).addClass("active");
				break;
			}
		}
		
		//给右边栏绑定事件
		function bindEventToRight(){
			// 清空操作
			$("#popsrli" + suffix + " > ul:eq(0) > li:eq(3)").click(function() {
				if(nodes.length > 0) {
					$.fn.zTree.getZTreeObj(treeId).checkAllNodes(false);
					clearAll();
				}
				delete JingoalTree.companyId;
			});
			
			$("#popsrli" + suffix + " > ul:eq(1)").click(function(event){
				if(JingoalTree.companyId){
					delete JingoalTree.companyId;
				}
				try {
					var nodeid = $(event.target).data('nodeid');
					removeNode(nodeid, true);
				} catch(e){}
			});
		}
		
		/**
		 * 
		 */
		function bindSendClick() {
			$("input[name='smsAwork" + suffix + "']").click(function(){
				if($("input[name='smsAwork" + suffix + "']").is(':checked')){
					$("#sms_awoke_div").css("display", "");
				}else{
					$("#sms_awoke_div").css("display", "none");
				}
			});
			$("#goBuy").click(function() {
				if(!!window.ActiveXObject && !window.XMLHttpRequest){  //ie6
					window.open("/module/purchase/index.do");
				} else {
					parent.parent.tm.tab.show('RA21B1');
				}
			});
		}
		
		// 判断指定的节点是否选中
		function isExistNode(id, type){
			type = getNodeType(type);
			var result = false;
			$.each(nodes,function(i,node){
				if (node.id == id && node.type == type) {
					result = true;
					return false;
				}
			});
			return result;
		}
		
		/**
		 * 添加一个用户到数组中并返回新数组，保证用户唯一性
		 * @param node
		 */
		function addNode(node){
			//显示到右面板中
			if(document.getElementById('uid_' + node.id + "-" + node.type) == null){
				nodes.push(node);
				
				var iconClass = 'ico_employee';
				if (node.type == 'dept') {
					iconClass = 'ico_dept';
				} else if (node.type == 'duty') {
					iconClass = 'ico_duty';
				}
				
				var $nodeli;
				if(node.fromEnc){
					$nodeli = $("<li id='uid_" + node.id + "-" + node.type + "' data-nodeid='" + node.id + "-" + node.type + "' class='clearfix "+iconClass+"'></li>")
						.append("<a title='" + node.name + "' data-nodeid='" + node.id  + "-" + node.type + "'>" + node.name + "(友)</a>")
						.append("<span data-nodeid='" + node.id + "-" + node.type + "' class='dialogtree-close'></span>");
				} else {
					$nodeli = $("<li id='uid_" + node.id + "-" + node.type + "' data-nodeid='" + node.id + "-" + node.type + "' class='clearfix "+iconClass+"'></li>")
						.append("<a title='" + node.name + "' data-nodeid='" + node.id + "-" + node.type + "'>" + node.name + "</a>")
						.append("<span data-nodeid='" + node.id + "-" + node.type + "' class='dialogtree-close'></span>");
				}
				$("#popsrli" + suffix + " > ul:eq(1)").append($nodeli);
			}
			resetSelectTip();
		}
		
		/**
		 * 移除一个用户
		 * @param nodeid
		 * @param sync
		 */
		function removeNode(nodeid, sync){
		
			var uid = nodeid.split('-')[0];
			if($('#uid_' + nodeid).length > 0){
				$('#uid_' + nodeid).remove();
				var index = -1;
				for(var i = 0;i < nodes.length;i++){
					if(nodes[i].id == uid){
						index = i;
						break;
					}
				}
				
				if(index >= 0){
					nodes.splice(index, 1);
				}
				
				if(sync){
					var tree = $.fn.zTree.getZTreeObj(treeId); //可以优化
					var node = tree.getNodesByFilter(function(n){
						if(n.id == uid){
							return true;
						}
						return false;
					}, true);
					
					if(node != null){
						tree.checkNode(node, false, true);
					}
				}
				
				// 恢复搜索添加
				var type = nodeid.split('-')[1];
				var $node = $("#node_" + suffix + type + uid.split('-')[0]);
				if ($node.length > 0) {
					$node.removeClass('text');
					$node.html("<button class='btn'>" + newtree_lang.add + "</button>");
				}
			}
			
			resetSelectTip();
		}
		
		function resetSelectTip(){
			$("#nodeSelected" + suffix).text(nodes.length);
			if (nodes.length > option.maxSelectTip && 
					nodes.length <= option.maxSelect) {
				$("#nodeSelected" + suffix).removeClass("remark_r");
				$("#selected0" + suffix).removeClass("hide");
				$("#selected1" + suffix).addClass("hide");
				$("#nodeRemainSelected" + suffix).text(option.maxSelect - nodes.length);
			}
			
			// 大于最大选择树
			if (nodes.length > option.maxSelect) {
				$("#nodeSelected" + suffix).addClass("remark_r");
				$("#selected0" + suffix).addClass("hide");
				$("#selected1" + suffix).removeClass("hide");
				$("#nodeOverSelected" + suffix).text(nodes.length - option.maxSelect);
			}
			
			if (nodes.length <= option.maxSelectTip) {
				$("#nodeSelected" + suffix).removeClass("remark_r");
				$("#selected0" + suffix).addClass("hide");
				$("#selected1" + suffix).addClass("hide");
			}
		}
		
		function getNodeIds(type){
			var ids = [];
			for(var i = 0;i < nodes.length;i++){
				if (nodes[i].type == type) {
					ids.push(nodes[i].id);	
				}
			}
			return ids;
		};
		
		function getNodeNames(type){
			var names = [];
			for(var i = 0;i < nodes.length;i++){
				if (nodes[i].type == type) {
					names.push(nodes[i].name);
				}
			}
			return names;
		};
		
		function clearAll(){
			$('.eledlist').html('');
			nodes = [] ;
			resetSelectTip();
		}
		
		this.getSelectedUids = function(){ return getNodeIds('employee'); };
		this.getSelectedDeptIds = function() { return getNodeIds('dept'); };
		this.getSelectedDutyIds = function(){ return getNodeIds('duty'); };
		this.getSelectedCompanyId = function(){ return JingoalTree.companyId;};
		
		this.getSelectedUnames = function(){ return getNodeNames('employee'); };
		this.getSelectedDeptNames = function(){ return getNodeNames('dept'); };
		this.getSelectedDutyNames = function(){ return getNodeNames('duty'); };
		
		this.getSelectedAllNames = function(){
			var names = [];
			if(nodes.length == 1 && nodes[0].type ==  getNodeType(NODE_TYPE_COMPANY)){
				return newtree_lang.allEmpText;
			}else{
				var deptNames = [] , dutyNames = [] , empNames = [] ;
				
				for(var i = 0;i < nodes.length;i++){
					if (nodes[i].type == "dept") {
						deptNames.push(nodes[i].name);
					}else if(nodes[i].type == "duty"){
						dutyNames.push(nodes[i].name);
					}else{
						empNames.push(nodes[i].name);
					}
				}
				return names.concat(deptNames,dutyNames , empNames);
			}
		}
		
		this.getSelectNodes = function() { return nodes };
		
		this.destroy = function(){
			if(option.isDialog){
				removeJingoalTreeFromWindow(suffix);
				if(option.callCancelback){
					option.callCancelback();
				}
			}
			
		};
		
		return this;
	}
})());